﻿using SuperX.Common.Log;
using SuperX.DataCenterService.RabbitMQ.Model;
using SuperX.MiddlewareBase;
using SuperX.ORM;
using Newtonsoft.Json;
using System;

namespace SuperX.DataCenterService.RabbitMQ
{
    public class RabbitMQManager : ManagerBase
    {
        /// <summary>
        /// 配置文件
        /// </summary>
        public DataCenterConfig RunTimeRabbitMQ { get; set; }

        public RabbitMQManager(DataCenterConfig config)
        {
            Name = "RabbitMQ";
            RunTimeRabbitMQ = JsonConvert.DeserializeObject<DataCenterConfig>(JsonConvert.SerializeObject(config));
        }

        public override void Init()
        {
            try
            {
                foreach (var hostItems in RunTimeRabbitMQ.RabbitMQHosts)
                {
                    if (!hostItems.IsEnable) continue;
                    RabbitHost host = new RabbitHost(hostItems);
                    foreach (var item in hostItems.ChannelItems)
                    {
                        host.Channels.Add(new RabbitChannel(item));
                    }
                    Hosts.Add(host);
                }
                LoadHost();
                Db = new DBClient().CreateClientByCustom<DataCache>("RabbitMQ");
            }
            catch (Exception ex)
            {
                Logger.ErrorException(ex);
            }
            base.Init();
        }

        public void LoadHost()
        {
            foreach (RabbitHost host in Hosts)//初始化MQ连接
            {
                host.Init();
            }
        }
    }
}